
const Helper = {

}
export default Helper

// import FileSaver from 'file-saver';
// import XLSX from 'xlsx'

/**
 * date转string 可规定转换格式
 */
Helper.dateFormat = (fmt, time) => {
    let date = Helper.toDate(time);
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "M+": (date.getMonth() + 1).toString(), // 月
        "D+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "m+": date.getMinutes().toString(), // 分
        "s+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

/**
 * string转date 
 * 2021-05-06 12:24:40  Thu May 06 2021 12:24:40 GMT+0800 (中国标准时间)
 * 2021                 Fri Jan 01 2021 08:00:00 GMT+0800 (中国标准时间)
 * 2021-05              Sat May 01 2021 00:00:00 GMT+0800 (中国标准时间)
 * 2021-05-06           Thu May 06 2021 00:00:00 GMT+0800 (中国标准时间)
 */
Helper.parserDate = (string) => {
    //兼容在手机上转换
    if (Helper.isEmpty(string)) {
        return new Date();
    }
    var a = string.split(" ");
    if (a.length == 2) {
        var b = a[0].split("-");
        var c = a[1].split(":");
        if (c.length == 1) {
            return new Date(b[0], b[1] - 1, b[2], c[0]);
        } else if (c.length == 2) {
            return new Date(b[0], b[1] - 1, b[2], c[0], c[1]);
        } else if (c.length == 3) {
            return new Date(b[0], b[1] - 1, b[2], c[0], c[1], c[2]);
        }
    } else if (a.length == 1) {
        var b = a[0].split("-");
        if (b.length == 1) {
            return new Date(b[0]);
        } else if (b.length == 2) {
            return new Date(b[0], b[1] - 1);
        } else if (b.length == 3) {
            return new Date(b[0], b[1] - 1, b[2]);
        }
    } else {
        return new Date(Date.parse(string.replace(/-/g, "/")));
    }


}
/**
 * 获取年的第一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getYearFirstDay = (date) => {
    var firstDay = Helper.toDate(date);
    firstDay.setMonth(0);
    firstDay.setDate(1);
    firstDay = Helper.dateFormat("YYYY-MM-DD", firstDay);
    return firstDay;
}
/**
 * 获取年的最后一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getYearLastDay = (date) => {
    var lastDay = Helper.toDate(date);
    lastDay.setFullYear(lastDay.getFullYear() + 1);
    lastDay.setMonth(0);
    lastDay.setDate(0);
    lastDay = Helper.dateFormat("YYYY-MM-DD", lastDay);
    return lastDay;
}

/**
 * 获取季度的第一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getSeasonFirstDay = (date) => {
    var firstDay = Helper.toDate(date);
    var month = firstDay.getMonth();
    if (month < 3) {
        firstDay.setMonth(0);
    } else if (2 < month && month < 6) {
        firstDay.setMonth(3);
    } else if (5 < month && month < 9) {
        firstDay.setMonth(6);
    } else if (8 < month && month < 11) {
        firstDay.setMonth(9);
    }
    firstDay.setDate(1);
    return Helper.dateFormat("YYYY-MM-DD", firstDay);
}

/**
 * 获取季度的最后一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getSeasonLastDay = (date) => {
    var lastDay = Helper.toDate(date);
    var month = lastDay.getMonth();
    if (month < 3) {
        lastDay.setMonth(2);
    } else if (2 < month && month < 6) {
        lastDay.setMonth(5);
    } else if (5 < month && month < 9) {
        lastDay.setMonth(8);
    } else if (8 < month && month < 11) {
        lastDay.setMonth(11);
    }
    return Helper.getMonthLastDay(lastDay);
}

/**
 * 获取月的第一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getMonthFirstDay = (date) => {
    var firstDay = Helper.toDate(date);
    firstDay.setDate(1);
    return Helper.dateFormat("YYYY-MM-DD", firstDay);
}

/**
 * 获取月的最后一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getMonthLastDay = (date) => {
    var lastDay = Helper.toDate(date);
    // lastDay.setMonth(lastDay.getMonth() + 1);
    // console.log(lastDay);
    // lastDay.setDate(0);
    var newDate = new Date(lastDay.getFullYear(), lastDay.getMonth() + 1, 0)
    return Helper.dateFormat("YYYY-MM-DD", newDate);
}


/**
 * 获取周的第一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getWeekFirstDay = (date) => {
    var firstDay = Helper.toDate(date);
    var weekday = firstDay.getDay() || 7; //获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7
    firstDay.setDate(firstDay.getDate() - weekday + 1); //往前算（weekday-1）天，年份、月份会自动变化
    return Helper.dateFormat("YYYY-MM-DD", firstDay);
}

/**
 * 获取周的第后一天
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getWeekLastDay = (date) => {
    var lastDay = Helper.toDate(date);
    var weekday = lastDay.getDay() || 7; //获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7
    lastDay.setDate(lastDay.getDate() - weekday + 7); //往前算（weekday-1）天，年份、月份会自动变化
    return Helper.dateFormat("YYYY-MM-DD", lastDay);
}

/**
 * 获取前后n小时
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD HH 格式
 */
Helper.getHourAround = (date, HourCount) => {
    var myDate = Helper.toDate(date);
    myDate.setTime(myDate.getTime() + 1000 * 60 * 60 * HourCount);
    return Helper.dateFormat("YYYY-MM-DD HH", myDate);
}

/**
 * 获取前后n天日期
 * 兼容 Date 和 String 类型
 * return YYYY-MM-DD 格式
 */
Helper.getDayAround = (date, dayCount) => {
    var myDate = Helper.toDate(date);
    myDate.setTime(myDate.getTime() + 1000 * 60 * 60 * 24 * dayCount);
    return Helper.dateFormat("YYYY-MM-DD", myDate);
}

/**
 * 获取前后n月日期
 * 兼容 Date 和 String 类型
 * return YYYY-MM 格式
 */
Helper.getMonthAround = (date, monthCount) => {
    var myDate = Helper.toDate(date);
    myDate.setMonth(myDate.getMonth() + monthCount);
    return Helper.dateFormat("YYYY-MM", myDate);
}


/**
 * 获取前后n年日期
 * 兼容 Date 和 String 类型
 * return YYYY 格式
 */
Helper.getYearAround = (date, yearCount) => {
    var myDate = Helper.toDate(date);
    myDate.setFullYear(myDate.getFullYear() + yearCount);
    return Helper.dateFormat("YYYY", myDate);
}

/**
 * 获取时间间隔
 * 兼容 Date 和 String 类型
 * return 天 格式
 */
Helper.getDiffDay = (start, end) => {
    var startTime = Helper.toDate(start);
    var endTime = Helper.toDate(end);
    let diffDate = Math.abs(endTime - startTime);
    let total = Math.floor(diffDate / (1000 * 3600 * 24));
    return total;
}

/**
 * 
 * @param {*} date 
 * @returns 
 */
Helper.getWeekDate = (date) => {
    var myDate = Helper.toDate(date);
    var day = myDate.getDay();
    var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
    var week = weeks[day];
    return week;
}

/**
 * String 和 Date 都转Date
 */
Helper.toDate = (date) => {
    var myDate = new Date();
    if (date instanceof Date) {
        myDate = new Date(date);
    } else {
        myDate = Helper.parserDate(date);
    }
    return myDate;
}

Helper.getUserInfo = () => {
    return JSON.parse(sessionStorage.getItem("userInfo"));
}

/**
 * 
 * @param {*} minNum 最小值
 * @param {*} maxNum 最小值
 * @param {*} decimalNum 保留小数位
 * @returns 
 */
Helper.randomNum = (minNum, maxNum, decimalNum) => {
    var max = 0,
        min = 0;
    minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum);
    switch (arguments.length) {
        case 1:
            return Math.floor(Math.random() * (max + 1));
        case 2:
            return Math.floor(Math.random() * (max - min + 1) + min);
        case 3:
            return (Math.random() * (max - min) + min).toFixed(decimalNum);
        default:
            return Math.random();
    }
}

Helper.getID = () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01

    var uuid = s.join("");
    return uuid;
    //  return new Date().getTime() + Helper.randomNum(1000,9999,0);
}
/**
 * 
 * @param {*} obj 判断是否为空
 * @returns 
 */
Helper.isEmpty = (obj) => {
    if (typeof obj === "undefined" || obj === null || obj === "" || obj === "NaN" || obj === "null" || obj === "undefined" || obj === "none") {
        return true;
    } else if (Object.prototype.toString.call(obj) == "[object Array]") {
        if (obj.length == 0) {
            return true;
        } else {
            return false;
        }

    } else if (Object.prototype.toString.call(obj) == "[object Object]") {
        if (JSON.stringify(obj) == '{}') {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}

/**
 * 通常用在展示数据时,为空则用--代替
 * @param {*} obj 
 * @returns 
 */
Helper.showValue = (obj) => {
    if (Helper.isEmpty(obj)) {
        return "--";
    } else {
        return obj;
    }
}

/**
 * 使用replace值替换空值
 * @param {*} obj 
 * @param {*} replace 
 * @returns 
 */
Helper.replaceIfObjisNull = (obj, replace) => {
    if (Helper.isEmpty(obj)) {
        return replace;
    } else {
        return obj;
    }
}

/**
 * 根据key值从小到大排列
 * @param {*} array 
 * @param {*} key 
 * @returns 
 */
Helper.upSortByKey = (array, key) => {
    return array.sort(function (a, b) {
        var x = parseFloat(a[key]);
        var y = parseFloat(b[key]);
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    })
}

/**
 * 根据key值从大到小排列
 * @param {*} array 
 * @param {*} key 
 * @returns 
 */
Helper.downSortByKey = (array, key) => {
    return array.sort(function (a, b) {
        var x = parseFloat(a[key]);
        var y = parseFloat(b[key]);
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    })
}

/**
 * 根据key值从小到大排列
 * @param {*} array 
 * @param {*} key 
 * @returns 
 */
Helper.upSortTimeByKey = (array, key) => {
    return array.sort(function (a, b) {
        let x = new Date(a[key]).getTime();
        let y = new Date(b[key]).getTime();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    })
}

/**
 * 根据key值从大到小排列
 * @param {*} array 
 * @param {*} key 
 * @returns 
 */
Helper.downSortTimeByKey = (array, key) => {
    return array.sort(function (a, b) {
        let x = new Date(a[key]).getTime();
        let y = new Date(b[key]).getTime();
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    })
}

/**
 * 深度克隆对象、数组
 * @param obj 被克隆的对象
 * @return 克隆后的对象
 */
Helper.cloneObject = (obj) => {
    return JSON.parse(JSON.stringify(obj))
}

/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间（只会生成传入的字符串中的字符）
 * @return string 生成的字符串
 */
Helper.randomString = (length, chats) => {
    if (!length) length = 1;
    if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
    let str = '';
    for (let i = 0; i < length; i++) {
        let num = Helper.randomNum(0, chats.length - 1, 0);
        str += chats[num];
    }
    return str;
}

Helper.deleteElement = (array, key, value) => {
    var i = "";
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element[key] == value) {
            i = index;
        }
    }
    array.splice(i, 1);
}

/**
 * 随机生成uuid
 * @return string 生成的uuid
 */
Helper.randomUUID = () => {
    let chats = '0123456789abcdef';
    return randomString(32, chats);
}


Helper.getMapArrayLabel = (array, res, value = "value", label = "label") => {
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element[value] == res) {
            return element[label];
        }
    }
}

/**
 * 通过a标签下载文件
*/
Helper.useALoadFile = (url, fileName) => {
    var a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    a.click();
    // console.log(url);
    window.URL.revokeObjectURL(url);
}
/**
 * 下载二进制留文件
*/
Helper.loadBlobFile = (blob, fileName) => {
    var url = window.URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
}

Helper.addDecimalNum = (num1, num2) => {
    num1 == undefined ? num1 = 0 : ''
    num2 == undefined ? num2 = 0 : ''
    var sq1, sq2, m;
    try {
        sq1 = num1.toString().split(".")[1].length;
    }
    catch (e) {
        sq1 = 0;
    }
    try {
        sq2 = num2.toString().split(".")[1].length;
    }
    catch (e) {
        sq2 = 0;
    }
    m = Math.pow(10, Math.max(sq1, sq2));
    return (num1 * m + num2 * m) / m;
}

/**
 * 选择文件
*/
Helper.chooseFile = (accept, multiple) => {
    if (document.querySelector('#file')) {//如果已存在,先移除
        document.querySelector('#file').remove();
    }
    var inputObj = document.createElement('input')
    inputObj.setAttribute('id', 'file');
    inputObj.setAttribute('type', 'file');
    inputObj.setAttribute('name', 'file');
    inputObj.setAttribute('accept', accept ? accept : '');
    if (multiple) {
        inputObj.setAttribute('multiple', true);
    }
    inputObj.setAttribute('style', 'display:none;');
    document.body.appendChild(inputObj);
    inputObj.value;
    inputObj.click();
}
//去除children这个字段
Helper.formatSites = (result) => {
    for (let index = 0; index < result.length; index++) {
        const element = result[index];
        if (element.children.length == 0) {
            delete element.children;
        } else {
            Helper.formatSites(element.children);
        }
    }
}

/**
 * a-tree搜索
 * treeData 是树形结构数据
 * searchText 搜索关键字
 * expandedKeys 展开的节点key,与a-tree绑定的值
 * fieldNames 数据转换配置
*/
Helper.filterTree = (treeData, searchText, expandedKeys, fieldNames) => {
    if (Helper.isEmpty(fieldNames)) {
        fieldNames = { title: "title", key: "key" }
    }
    if (Helper.isEmpty(expandedKeys)) {
        expandedKeys = [];
    }
    //深拷贝一份
    let tree = Helper.cloneObject(treeData);
    //递归得到平铺数组，并添加上父id，都添加隐藏节点
    let flattenArray = [];

    function flatten(nodes, parentKey = "") {
        for (const node of nodes) {
            Reflect.set(node, "style", "display:none");
            if (parentKey) {
                Reflect.set(node, "parentKey", parentKey);
            }
            let dic = {
                title: node[fieldNames.title],
                key: node[fieldNames.key],
                parentKey: node.parentKey || "",
            }
            flattenArray.push(dic);
            if (node.hasOwnProperty('children') && node.children.length > 0) {
                flatten(node.children, node[fieldNames.key]);
            }
        }
    }
    flatten(tree);
    //获取搜索到的节点和节点id集合
    let searchNodes = [];
    let searchKeys = [];
    flattenArray.forEach(element => {
        if (element.title.indexOf(searchText) !== -1) {
            searchNodes.push(element);
            searchKeys.push(element.key);
        }
    });
    //递归平铺数组，得到搜索到的节点的所有父节点
    let parentKeys = [];
    searchNodes.forEach(element => {
        function findparentKeys(parentKey) {
            flattenArray.forEach(item => {
                if (parentKey == item.key && parentKeys.indexOf(parentKey) == -1) {
                    parentKeys.push(parentKey);
                    if (item.parentKey) {
                        findparentKeys(item.parentKey);
                    }
                }
            })
        }
        if (element.parentKey) {
            findparentKeys(element.parentKey);
        }
    });
    let allDisplayKeys = [...searchKeys];
    //把父节点和搜索到的节点集合合并，得到需要显示的节点集合
    for (const parentKey of parentKeys) {
        if (allDisplayKeys.indexOf(parentKey) == -1) {
            allDisplayKeys.push(parentKey);
        }
    }
    //递归，把需要显示的节点的隐藏属性删除，就可以显示出搜索到的节点
    for (const key of allDisplayKeys) {
        function displayNode(nodes) {
            for (const node of nodes) {
                if (node[fieldNames.key] == key) {
                    Reflect.deleteProperty(node, "style");
                }
                if (node.hasOwnProperty('children') && node.children.length > 0) {
                    displayNode(node.children);
                }
            }
        }
        displayNode(tree);
    }
    //获取需要展开的节点
    let expandedKeysTemp = [...parentKeys];
    if (Helper.isEmpty(searchText)) {
        expandedKeysTemp = [];
    }
    for (const key of expandedKeysTemp) {
        if (expandedKeys.indexOf(key) == -1) {
            expandedKeys.push(key);
        }
    }
    return { treeData: tree, expandedKeys: expandedKeys };
}


Helper.animateCSS = (node, animation, prefix = 'animate__') => {
    return new Promise((resolve, reject) => {
        const animationName = `${prefix}${animation}`;
        node.classList.add(`${prefix}animated`, animationName);
        // When the animation ends, we clean the classes and resolve the Promise
        function handleAnimationEnd(event) {
            event.stopPropagation();
            node.classList.remove(`${prefix}animated`, animationName);
            resolve('Animation ended');
        }

        node.addEventListener('animationend', handleAnimationEnd, { once: true });
    });
}
